import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/utils/api'
import { storeLogger } from '@/utils/logger'

export const useJarsStore = defineStore('jars', () => {
  // 状态
  const jars = ref([])
  const loading = ref(false)
  const total = ref(0)
  const currentPage = ref(1)
  const pageSize = ref(20)
  const searchForm = ref({
    name: '',
    entry: ''
  })

  // 计算属性
  const filteredJars = computed(() => {
    let result = jars.value

    if (searchForm.value.name) {
      result = result.filter(jar => 
        jar.name.toLowerCase().includes(searchForm.value.name.toLowerCase())
      )
    }

    if (searchForm.value.entry) {
      result = result.filter(jar => 
        jar.entry && jar.entry.toLowerCase().includes(searchForm.value.entry.toLowerCase())
      )
    }

    return result
  })

  // 方法
  const fetchJars = async () => {
    try {
      loading.value = true
      const response = await api.get('/jars')
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload
      const list = data.jars || []
      jars.value = list
      total.value = list.length
    } catch (error) {
      storeLogger.error('获取JAR列表失败:', error)
      ElMessage.error('获取JAR列表失败')
      jars.value = []
      total.value = 0
    } finally {
      loading.value = false
    }
  }

  const uploadJar = async (file) => {
    try {
      loading.value = true
      const formData = new FormData()
      formData.append('jarfile', file)
      
      const response = await api.post('/jars/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      
      if (response.data) {
        ElMessage.success('JAR包上传成功')
        await fetchJars() // 重新获取列表
        return response.data
      }
    } catch (error) {
      storeLogger.error('JAR包上传失败:', error)
      ElMessage.error('JAR包上传失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  const deleteJar = async (jarId) => {
    try {
      loading.value = true
      await api.post(`/jars/${jarId}/delete`)
      ElMessage.success('JAR包删除成功')
      await fetchJars() // 重新获取列表
    } catch (error) {
      storeLogger.error('JAR包删除失败:', error)
      ElMessage.error('JAR包删除失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  const deleteAllJars = async () => {
    try {
      loading.value = true
      await api.post('/jars/delete-all')
      ElMessage.success('所有JAR包已删除')
      await fetchJars() // 重新获取列表
    } catch (error) {
      storeLogger.error('删除所有JAR包失败:', error)
      ElMessage.error('删除所有JAR包失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  const resetSearch = () => {
    searchForm.value = {
      name: '',
      entry: ''
    }
    currentPage.value = 1
  }

  const setPage = (page) => {
    currentPage.value = page
  }

  const setPageSize = (size) => {
    pageSize.value = size
    currentPage.value = 1
  }

  return {
    // 状态
    jars,
    loading,
    total,
    currentPage,
    pageSize,
    searchForm,
    
    // 计算属性
    filteredJars,
    
    // 方法
    fetchJars,
    uploadJar,
    deleteJar,
    deleteAllJars,
    resetSearch,
    setPage,
    setPageSize
  }
})
